<template>
  <div class="app-container">
    <el-tabs v-model="gatherType" type="border-card">
      <el-tab-pane label="Single" name="0" />
      <el-tab-pane label="Classified" name="1" />
    </el-tabs>
    <div class="topSearch">
      <el-row class="topRow">
        <div class="gather-box">
          <el-input
            v-if="gatherType === '0'"
            v-model="gatherData"
            type="textarea"
            style="width: 100%;padding:0;"
            :autosize="size"
            placeholder="Please fill in the web address of the product, and enter for multiple URLs"
          />
          <el-input
            v-if="gatherType === '1'"
            v-model="gatherData"
            type="text"
            style="width: 100%;padding:0"
            placeholder="Please fill in the website classified in the store"
          />
          <p class="gather-p">Currently supported：aliexpress,amazon</p>
          <div>
            <el-row class="gatherBtn">
              <el-button
                type="primary"
                size="mini"
                @click="startGather"
              >Start Collection</el-button>
              <el-button
                type="danger"
                size="mini"
                @click="clear"
              >Clear</el-button>
            </el-row>
          </div>
          <!-- <el-progress :text-inside="true" style="margin-top: 10px" :stroke-width="24" :percentage="70" status="success" />
          <p class="gather-status"><span>采集成功：10条</span> <span>采集失败：20条</span></p> -->
        </div>
      </el-row>
      <el-row>
        <el-select v-model="number" placeholder="Please Choose">
          <el-option
            v-for="item in numberOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-input
          v-model="searchContent"
          placeholder="Please Enter"
          style="width: 250px"
          class="input-with-select"
          @keyup.enter.native="searchNumber"
        >
          <i
            slot="suffix"
            style="cursor: pointer;"
            class="el-input__icon el-icon-search btn-search"
            @click="searchChange"
          />
        </el-input>
        <el-select
          v-model="searchCriteria.status"
          placeholder="Please Choose"
          clearable
          @change="searchChange"
        >
          <el-option
            v-for="item in statusOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-select
          v-model="searchCriteria.source"
          placeholder="Please Choose"
          clearable
          @change="searchChange"
        >
          <el-option
            v-for="item in sourceOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-row>
    </div>
    <el-row class="topRow">
      <div style="display: inline-block;margin-right: 10px;">
        <el-dropdown
          @command="
            (command) =>
              collectionStore(command, '')
          "
        >
          <el-button
            type="primary"
            size="mini"
          >Batch Claim<i
            class="el-icon-arrow-down el-icon--right"
          /></el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="1">shopify</el-dropdown-item>
            <el-dropdown-item command="2">wooc</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>
      <!-- <el-button type="primary" size="mini">批量认领</el-button> -->
      <el-button
        type="primary"
        size="mini"
        @click="deleteItem('')"
      >Batch Remove</el-button>
    </el-row>
    <el-table
      ref="multipleTable"
      v-loading="loading"
      :data="tableData"
      border
      style="width: 100%"
      @selection-change="handleSelectionChange"
      @row-click="rowClick"
    >
      <el-table-column type="selection" width="50" />
      <el-table-column label="ID" prop="productCollection.productId" />
      <el-table-column label="Iamge" width="100">
        <template slot-scope="scope">
          <el-image
            class="productImg"
            lazy
            :src="
              imgPrefix + scope.row.productCollection.thumbnailImage + imgSuffix
            "
            @click="
              toProview(
                scope.row.img.indexOf('http') === 0
                  ? scope.row.thumbnailImage
                  : imgPrefix + scope.row.productCollection.thumbnailImage
              )
            "
          >
            <div slot="placeholder" class="image-slot">
              <i class="el-icon-loading" />
            </div>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column prop="productCollection.title" label="Title">
        <template slot-scope="scope">
          <p :title="scope.row.productCollection.title" class="more-p">
            {{ scope.row.productCollection.title }}
          </p>
        </template>
      </el-table-column>
      <el-table-column prop="productCollection.salePrice" label="Price">
        <template slot-scope="scope">
          <span>{{
            scope.row.productCollection.salePrice
              ? scope.row.productCollection.salePrice / 100
              : 0
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="Source">
        <template slot-scope="scope">
          <p class="soure-p" @click="goStore(scope.row.source)">
            {{ splitUrl(scope.row.source) }}
          </p>
        </template>
      </el-table-column>
      <el-table-column prop="platformTypes" label="Claimed">
        <template slot-scope="scope">
          <p v-if="scope.row.platformTypes.length">
            <span v-for="item in scope.row.platformTypes" :key="item">{{
              item === 1 ? 'shopify' : 'wooc'
            }}</span>
          </p>
        </template>
      </el-table-column>
      <el-table-column prop="productCollection.createTime" label="CreateTime" />
      <el-table-column label="Operation" width="200">
        <template slot-scope="scope">
          <div>
            <el-dropdown
              size="small"
              split-button
              type="primary"
              @command="
                (command) =>
                  collectionStore(command, scope.row.productCollection.id)
              "
            >
              Claim
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="1">shopify</el-dropdown-item>
                <el-dropdown-item command="2">wooc</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
            <el-button
              type="primary"
              @click.stop="deleteItem(scope.row.id, 'one')"
            >Remove</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      id="btmPagination"
      :class="{ open: $store.state.app.sidebar.opened }"
      :current-page="currentPage"
      :page-sizes="[10, 30, 50, 100, 300, 500]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <!-- 开始采集加载 -->
    <load
      v-if="uploadLoad"
      :percent="percentage"
      :success="successCount"
      :error="errorCount"
      @loadClose="loadClose"
    />

    <!-- 图片预览 -->
    <proview-img v-if="proviewUrl" :src="proviewUrl" @close="closeProview" />
  </div>
</template>

<script>
import {
  collectionPage,
  collection,
  collectionDelete,
  collectionClaim
} from '@/api/product';
import { downloadUrl } from '@/utils/downLoad';
import ProviewImg from '@/components/Proview/proviewImg';
import Load from '@/components/loading/load';
import { postResult } from '@/utils/dataFormat';
export default {
  components: {
    ProviewImg,
    Load
  },
  data() {
    return {
      gatherType: '0',
      successCount: 0,
      errorCount: 0,
      searchContent: '',
      number: 1,
      size: { minRows: 5, maxRows: 8 },
      gatherData: '',
      percentage: 0,
      uploadLoad: false,
      searchCriteria: {
        source: '',
        status: ''
      },
      tableData: [],
      multipleSelection: [],
      loading: false,
      currentPage: 1,
      pageSize: 30,
      total: 0,
      proviewUrl: '',
      numberOptions: [
        { label: 'ID', value: 1 },
        { label: 'Title', value: 2 }
      ],
      statusOptions: [
        { label: 'All', value: '' },
        { label: 'Claimed', value: 0 },
        { label: 'Unclaimed', value: 1 }
      ],
      sourceOptions: [
        { label: 'All', value: '' },
        { label: 'aliexpress', value: 2 },
        { label: 'amazon', value: 3 }
      ]
    };
  },
  mounted() {
    this.init();
  },
  methods: {
    searchNumber(val) {
      if (this.number === 1) {
        this.searchCriteria.id = this.searchContent;
        this.searchCriteria.title = '';
      } else {
        this.searchCriteria.title = this.searchContent;
        this.searchCriteria.id = '';
      }
      this.init();
    },
    init() {
      this.loading = true;
      const params = {
        ...this.searchCriteria,
        pageNo: this.currentPage,
        pageSize: this.pageSize
      };
      collectionPage(params).then((res) => {
        if (res.code === 200) {
          this.loading = false;
          this.tableData = res.data.data;
          this.total = res.data.totalCount;
        }
      });
    },
    collectionStore(val, id) {
      if (!id && !this.multipleSelection.length) {
        this.$message.warning('Please select at least one product');
        return;
      }
      const productIds = this.multipleSelection.map((item) => item.productCollection.id);
      const parmars = {
        ids: id ? [id] : productIds,
        storeTypeId: parseInt(val)
      };
      collectionClaim(parmars).then((res) => {
        postResult(res, this.$message, this.init);
      });
    },
    splitUrl(url) {
      var splitPath = url.split('/');
      if (splitPath[2]) {
        splitPath = splitPath[2];
        return splitPath;
      } else {
        splitPath = '';
        return splitPath;
      }
    },
    startGather() {
      if (this.gatherData) {
        var snsArr = this.gatherData.split(/[(\r\n)\r\n]+/);
        snsArr.forEach((item, index) => {
          if (!item) {
            snsArr.splice(index, 1); // 删除空项
          }
        });
      } else {
        this.$message.warning('Please enter product website');
        return;
      }
      this.uploadLoad = true;
      collection({ paths: snsArr }).then((res) => {
        if (res.code === 200) {
          this.successCount = res.data;
          this.errorCount = snsArr.length - res.data;
          this.percentage = 100;
          this.init();
        } else {
          this.percentage = -1;
        }
      });
    },
    clear() {
      this.gatherData = '';
    },
    goStore(name) {
      downloadUrl(`${name}`);
    },
    searchChange() {
      this.currentPage = 1;
      this.init();
    },
    deleteItem(id, type) {
      const parmasId = [id] || this.multipleSelection;
      if (type !== 'one' && !parmasId.length) {
        this.$message.warning('Please select at least one product');
        return;
      }
      this.$confirm('This operation will permanently delete the item. Do you want to continue?', 'warning', {
        confirmButtonText: 'ok',
        cancelButtonText: 'cancel',
        type: 'warning'
      })
        .then(() => {
          collectionDelete(parmasId).then((res) => {
            postResult(res, this.$message, this.init);
          });
        })
        .catch(() => {
          this.$message.info('Cancelled');
        });
    },
    loadClose() {
      this.uploadLoad = false;
      this.percentage = 0;
    },
    toProview(url) {
      // 预览图片
      this.proviewUrl = url;
    },
    closeProview() {
      this.proviewUrl = '';
      document.querySelector('body').removeAttribute('style');
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    rowClick(row, column, event) {
      if (column.label === 'Iamge') {
        return;
      }
      this.$refs.multipleTable.toggleRowSelection(row);
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.init();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.init();
    }
  }
};
</script>
<style lang="scss" scoped>
// ::v-deep .el-button + .el-button {
//   margin: 0;
// }
// .topSearch .el-button,
// .topSearch .el-select,
// .topSearch .el-input,
// .topSearch .el-upload {
//   margin: 2px;
// }
.topRow {
  margin-bottom: 10px;
}
.gather-box {
  border: 1px solid #dcdfe6;
  padding: 10px;
}
.gatherBtn {
  text-align: right;
  margin-top: 10px;
}
.gather-status {
  text-align: center;
  margin-top: 20px;
  color: #676767;
}
.gather-status span:nth-child(1) {
  color: #67c23a;
  padding-right: 20px;
}
.gather-status span:nth-child(2) {
  color: red;
}
.gather-p {
  color: #676767;
  font-size: 12px;
  float: left;
  padding-top: 10px;
}
.el-dropdown-link {
  cursor: pointer;
  color: #409eff;
}
.el-icon-arrow-down {
  font-size: 12px;
}
.more-p {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
}
.soure-p {
  cursor: pointer;
  &:hover {
    color: #16ad61;
  }
}
::v-deep .el-textarea__inner {
  border-radius: 0;
  // border-top: 0
}
::v-deep .el-tabs--border-card > .el-tabs__content {
  padding: 0;
}
::v-deep .el-tabs--border-card > .el-tabs__header {
  border: 0;
}
::v-deep .el-tabs--border-card {
  box-shadow: none;
  -webkit-box-shadow: none;
}
::v-deep .el-input__inner {
  border-radius: 0;
}

::v-deep .el-dropdown .el-button-group .el-button {
  padding: 4px;
}
// ::v-deep .el-dropdown__caret-button {
//   padding: 3.5px;
//   margin: 0;
//   vertical-align: top;
// }
::v-deep .el-dropdown__caret-button {
  padding: 3.5px !important;
  margin: 0 5px;
  vertical-align: top;
}
::v-deep .cell .el-button {
  padding: 4px 15px;
}
::v-deep .el-table .cell {
  text-align: center;
}
</style>
